<script setup>
import {getSurveysStatusText, goPreviewSurveys} from "../../utils/CommonsUtil.js";
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {
    copySurveysApi,
    deleteSurveysApi,
    getSurveysByIdApi,
    updateSurveysApi
} from "../../apis/SurveysApi.js";
import {Message, Modal} from "@arco-design/web-vue";
import {BASE_URL} from "../../config/index.js";
import {getTempLateListApi} from "../../apis/TemplateApi.js";
import __ from "lodash";

const router = useRouter()
const templateList = ref([])
const uploadList = ref([])
const coverUploadList = ref([])
const page = ref(1)
const size = ref(10)
const formRef = ref()
const isShowConfig = ref(false)
const form = ref({})
const searchInput = ref('')
const searchStatus = ref(-1)
//问卷标签输入框内容
const formTemplateTags = ref([])
const searchTemplateTags = ref([])
const pagination = ref({
    current: page.value,
    pageSize: size.value,
    total: 0, // 总条数初始为0
    showTotal: true, // 显示总数
    showPageSize: true, // 显示页码切换器
    showJumper: true, // 显示快速跳转
});
const dataLoading = ref(false);
// 修改后的获取数据方法
const getTemplateList = async () => {
    dataLoading.value = true
    let req = {}
    if (!__.isEmpty(searchInput.value)){
        req.title = searchInput.value
    }
    if (searchStatus.value !== -1){
        req.status = searchStatus.value
    }
    if (searchTemplateTags.value.length > 0){
        req.tags = JSON.stringify(searchTemplateTags.value)
    }
    const res = await getTempLateListApi(pagination.value.current,
                        pagination.value.pageSize, req)
    if (res.code === 0) {
        templateList.value = res.data.records
        pagination.value.total = Number(res.data.total)
    } else {
        Message.error(res.message)
    }
    dataLoading.value = false
}

const saveConfig = async () => {
    console.log('保存配置', form.value)
    //校验
    formRef.value.validate()
    //标签格式化为字符串
    form.value.tags = JSON.stringify(formTemplateTags.value)
    //请求
    const res = await updateSurveysApi(form.value)
    if (res.code === 0) {
        Message.success('保存成功')
        isShowConfig.value = false
        formTemplateTags.value = []
        await getTemplateList()
        return true
    } else {
        Message.error(res.message)
        formTemplateTags.value = []
        return false
    }

};

const handleShare = (data) => {
    goPreviewSurveys(data.id)
};

const handleConfig = async (id) => {
    const res = await getSurveysByIdApi(id)
    if (res.code === 0) {
        form.value = res.data
        if (!__.isEmpty(res.data.tags)){
            try {
                formTemplateTags.value = JSON.parse(res.data.tags)
            }catch (e){
                Message.error('模板标签解析失败,已清空')
                formTemplateTags.value = []
            }
        }
        uploadList.value = []
        isShowConfig.value = true
    }else{
        Message.error(res.message)
    }

};


const handleEdit = (id) => {
    router.push(`/workbench/${id}`)
};
const removeUpload = (file) => {
    uploadList.value = []
    form.value.bgimg = ''
    return true
}
const removeCoverUpload = (file) => {
    coverUploadList.value = []
    form.value.cover = ''
    return true
}

const handleDelete = async (id) => {
    try {
        Modal.warning({
            title: '警告',
            content: '删除后问卷数据无法还原 确认删除吗？',
            onOk: async () => {
                const res = await deleteSurveysApi(id)
                if (res.code === 0) {
                    Message.success('删除成功');
                } else {
                    Message.error(res.message);
                }
                await getTemplateList(); // 刷新列表
            },
        });
    } catch (error) {
        Message.error('删除失败');
    }
};

// 处理分页变化事件
const handlePageChange = (current) => {
    pagination.value.current = current
    getTemplateList()
}
const timeOk = (time) => {
    form.value.starttime = time[0]
    form.value.endtime = time[1]
};
// 处理每页数量变化事件
const handlePageSizeChange = (pageSize) => {
    pagination.value.pageSize = pageSize
    getTemplateList()
}

const uploadSuccess = (res) => {
    form.value.bgimg = res.response.data.url
}
const uploadCoverSuccess = (res) => {
    form.value.cover = res.response.data.url
}
const createTemplate = () => {
    //携带t=1 参数表示为创建模板
    router.push("/workbench?t=1")
}

onMounted(async () => {
    await getTemplateList()
})
</script>

<template>
    <div class="py-8 px-24">
        <div>
            <a-button type="primary" @click="createTemplate">创建模板</a-button>

            <a-select @change="getTemplateList()" v-model="searchStatus" class="ml-8" :style="{width:'120px'}" placeholder="状态">
                <a-option :value="-1" >全部</a-option>
                <a-option :value="0" >未发布</a-option>
                <a-option :value="1" >已发布</a-option>
                <a-option :value="2" >已关闭</a-option>
            </a-select>

            <a-input-tag v-model="searchTemplateTags"
                         class="ml-4"
                         size="medium"
                         :style="{width:'250px'}"
                         placeholder="根据标签搜索"
                         unique-value allow-clear/>

            <a-input-search @search="getTemplateList" v-model="searchInput" class="ml-8" :style="{width:'360px'}"
                            placeholder="搜索模板" search-button>
                <template #button-icon>
                    <icon-search/>
                </template>
                <template #button-default>
                    搜索
                </template>
            </a-input-search>
        </div>
        <a-table
            :scroll="{x:2000,y:900}"
            :loading="dataLoading"
            bordered
            stripe
            :data="templateList"
            :pagination="pagination"
            @page-change="handlePageChange"
            @page-size-change="handlePageSizeChange"
            class="mt-4"
        >
            <template #columns>
                <!-- 模板编号 -->
                <a-table-column
                    title="模板编号"
                    data-index="id"
                    :width="130"
                />

                <!-- 问卷标题 -->
                <a-table-column
                    title="标题"
                    data-index="title"
                    :width="150"
                />
                <!-- 问卷状态 -->
                <a-table-column
                    title="状态"
                    data-index="status"
                    :width="110"
                >
                    <template #cell="{ record }">
                        <a-tag color="#7bc616" v-if="record.status === 0"> {{ getSurveysStatusText(record.status)}}</a-tag>
                        <a-tag color="#165dff" v-if="record.status === 1"> {{ getSurveysStatusText(record.status)}}</a-tag>
                        <a-tag color="#ff5722" v-if="record.status === 2"> {{ getSurveysStatusText(record.status)}}</a-tag>

                    </template>
                </a-table-column>
                <a-table-column
                    :width="100"
                    title="创建用户"
                    data-index="createUserName"
                    :ellipsis="true"
                />

                <a-table-column title="登录校验" data-index="isLogin" :width="120">
                    <template #cell="{ record }">
                        {{ record.isLogin === 1 ? '需要' : '不需要' }}
                    </template>
                </a-table-column>


                <!-- 创建时间 -->
                <a-table-column :sortable="{ sortDirections: ['ascend', 'descend']}" title="创建时间" data-index="createtime" :width="180">
                    <!--                    <template #cell="{ record }">-->
                    <!--                        {{ new Date(record.createtime).toLocaleString() }}-->
                    <!--                    </template>-->
                </a-table-column>
                <!-- 模板描述 -->
                <a-table-column
                    :width="120"
                    title="模板使用数"
                    data-index="templateNum"
                    :ellipsis="true"
                />
                <!-- 模板描述 -->
                <a-table-column
                    :width="220"
                    title="模板描述"
                    data-index="description"
                    :ellipsis="true"
                />


                <!-- 操作列 -->
                <a-table-column
                    title="操作"
                    :width="160"
                    fixed="right"
                >
                    <template #cell="{ record }">
                        <a-space>
                            <a-button
                                status="success"
                                type="primary"
                                size="mini"
                                @click="handleShare(record)"
                            >
                                预览
                            </a-button>

                            <a-button
                                type="primary"
                                size="mini"
                                @click="handleConfig(record.id)"
                            >
                                配置
                            </a-button>
                            <a-button
                                type="primary"
                                size="mini"
                                @click="handleEdit(record.id)"
                            >
                                编辑
                            </a-button>
                            <a-button
                                type="primary"
                                status="danger"
                                size="mini"
                                @click="handleDelete(record.id)"
                            >
                                删除
                            </a-button>
                        </a-space>
                    </template>
                </a-table-column>
            </template>
        </a-table>
    </div>

    <a-modal unmount-on-close v-model:visible="isShowConfig" :on-before-ok="saveConfig" ok-text="保存">
        <template #title>
            配置问卷
        </template>
        <div>
            <a-form ref="formRef" :model="form"  auto-label-width>
                <a-form-item field="title" label="标题"
                             :rules="[{required:true,message:'请输入标题'},{minLength:1,maxLength:20,message:'标题最大20字符'}]">
                    <a-input v-model="form.title" placeholder="请输入问卷标题" />
                </a-form-item>
                <a-form-item field="description" label="描述">
                    <a-input v-model="form.description" placeholder="" />
                </a-form-item>
                <a-form-item field="description" label="相关标签">
                    <a-input-tag v-model="formTemplateTags" placeholder="请输入问卷标签" unique-value allow-clear/>
                </a-form-item>

                <a-form-item field="isLogin" label="登录校验">
                    <a-switch v-model="form.isLogin" :checked-value="1" :unchecked-value="0" >
                        <template #checked>
                            ON
                        </template>
                        <template #unchecked>
                            OFF
                        </template>
                    </a-switch>
                </a-form-item>
                <a-form-item field="isRepeated" label="允许重复提交">
                    <a-switch v-model="form.isRepeated" :checked-value="1" :unchecked-value="0" >
                        <template #checked>
                            ON
                        </template>
                        <template #unchecked>
                            OFF
                        </template>
                    </a-switch>
                </a-form-item>
                <a-form-item field="status" label="状态">
                    <a-select v-model="form.status" :style="{width:'220px'}">
                        <a-option :value="0">未发布</a-option>
                        <a-option :value="1">发布中</a-option>
                        <a-option :value="2">已关闭</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="生效时间">
                    <a-range-picker
                        style="width: 360px; margin: 0 24px 24px 0;"
                        :model-value="[form.starttime, form.endtime]"
                        show-time
                        format="YYYY-MM-DD HH:mm"
                        @ok="timeOk"
                    />
                </a-form-item>
                <a-form-item field="bgimg" label="背景图片" >
                    <a-image
                        class="rounded-lg"
                        width="180"
                        :src="form.bgimg"
                    />
                    <a-upload
                        class="ml-4" :limit="1"
                        withCredentials
                        name="file"
                        accept="image/*"
                        :on-before-remove="removeUpload"
                        @success="uploadSuccess"
                        :action="BASE_URL + '/files/upload'"/>
                </a-form-item>

                <a-form-item field="cover" label="封面图片" >
                    <a-image
                        class="rounded-lg"
                        width="180"
                        :src="form.cover"
                    />
                    <a-upload
                        class="ml-4" :limit="1"
                        withCredentials
                        name="file"
                        accept="image/*"
                        :on-before-remove="removeCoverUpload"
                        @success="uploadCoverSuccess"
                        :action="BASE_URL + '/files/upload'"/>
                </a-form-item>
            </a-form>

        </div>
    </a-modal>


</template>

<style scoped>

</style>
